/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Canadian Weather.
 *
 * The Initial Developer of the Original Code is
 *   George Bradt.
 *
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   George Bradt.
 *
 * Credits:
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

var CanWeatherConditions = {
    updateNode: function (aElement, aContent) {
        // Shallow clone will not copy the content of the element.
        var newElement = aElement.cloneNode(false);

        // Insert the cloned element before the original.
        aElement.parentNode.insertBefore(newElement, aElement);

        // Remove the original element.
        aElement.parentNode.removeChild(aElement);

        // Append new content.
        newElement.appendChild(aContent);
    },

    capitalizeFirstChar: function (aString) {
        // Capitalize the first character of a string.
        return aString.charAt(0).toUpperCase() + aString.slice(1);
    }
};

// Handle user-defined event emitted from add-on code after site data
// is retrieved and parsed. Initialize panel elements.
self.port.on('show', function(aLanguage, aData) {
    // Localizations. Content scripts not yet supported by l10n.
    var detailsString;
    var colonString;
    
    if ( aLanguage == 'f' ) {
        // French.
        detailsString = 'Détails d\'Environnement Canada';
        colonString = ' :';
    }
    else {
        detailsString = 'Details at Environment Canada';
        colonString = ':';
    }
        
    // Header.
    CanWeatherConditions.updateNode(document.getElementById('canw-name'),
                                    document.createTextNode(aData.location.name));

    // Location.
    CanWeatherConditions.updateNode(document.getElementById('canw-station'),
                                    document.createTextNode(aData.location.station));
    CanWeatherConditions.updateNode(document.getElementById('canw-region'),
                                    document.createTextNode(aData.location.region));

    // Current conditions.
    CanWeatherConditions.updateNode(document.getElementById('canw-dateObserved'),
                                    document.createTextNode(aData.currentConditions.date));
    CanWeatherConditions.updateNode(document.getElementById('canw-temperature'),
                                    document.createTextNode(aData.currentConditions.temperature));
    CanWeatherConditions.updateNode(document.getElementById('canw-condition'),
                                    document.createTextNode(aData.currentConditions.condition));
    CanWeatherConditions.updateNode(document.getElementById('canw-windchill'),
                                    document.createTextNode(aData.currentConditions.windChill));
    CanWeatherConditions.updateNode(document.getElementById('canw-humidex'),
                                    document.createTextNode(aData.currentConditions.humidex));
    CanWeatherConditions.updateNode(document.getElementById('canw-pressure'),
                                    document.createTextNode(aData.currentConditions.pressure));
    CanWeatherConditions.updateNode(document.getElementById('canw-visibility'),
                                    document.createTextNode(aData.currentConditions.visibility));
    CanWeatherConditions.updateNode(document.getElementById('canw-dewpoint'),
                                    document.createTextNode(aData.currentConditions.dewpoint));
    CanWeatherConditions.updateNode(document.getElementById('canw-humidity'),
                                    document.createTextNode(aData.currentConditions.relativeHumidity));
    CanWeatherConditions.updateNode(document.getElementById('canw-wind'),
                                    document.createTextNode(aData.currentConditions.wind));

    // Warnings
    var warningsString = '';

    if ( aData.warnings.length > 0 ) {
        for ( let i = 1; i < aData.warnings.length; i++ ) {
            warningsString += aData.warnings[i].description + '\n';
        }

        CanWeatherConditions.updateNode(document.getElementById('canw-warnings'),
                                        document.createTextNode(warningsString));

        // URL.
        var anchor = document.createElement("a");
        anchor.setAttribute('target', '_blank');
        anchor.setAttribute('href', aData.warnings[0]);
        anchor.appendChild(document.createTextNode(detailsString));
        document.getElementById('canw-warnings').appendChild(anchor);
    }

    if ( !warningsString ) {
        CanWeatherConditions.updateNode(document.getElementById('canw-warnings'),
                                        document.createTextNode('N/A'));
    }

    // Forecast.
    var forecastTable = document.getElementById('canw-forecastTable');
    var forecastTableLength = forecastTable.rows.length;

    // Remove all but first two rows from forecast table.
    for ( let i = 0; i < forecastTableLength - 2; i++ ) {
        forecastTable.deleteRow(forecastTable.rows.length - 1);
    }

    CanWeatherConditions.updateNode(document.getElementById('canw-dateIssued'),
                                    document.createTextNode(aData.forecasts.date));

    var newRow, newCell, period, summary;

    for ( let i = 0; i < aData.forecasts.forecast.length; i++ ) {
        newRow = forecastTable.insertRow(-1);

        newCell = newRow.insertCell(0);
        period = document.createTextNode(CanWeatherConditions.capitalizeFirstChar(aData.forecasts.forecast[i].period) + colonString);
        newCell.appendChild(period);

        newCell = newRow.insertCell(1);
        newCell.id = 'id' + i;
        summary  = document.createTextNode(aData.forecasts.forecast[i].summary);
        newCell.appendChild(summary);
    }
});

// Add event listener to our Ok button.
document.getElementById('canw-buttonOk').addEventListener('click', function(aEvent) {
    self.port.emit('ok-click');
    aEvent.preventDefault();
}, true);
